import { MAIN_APP_NAMES } from "../micro_apps/index";

// 要隐藏左侧显示的菜单alias
const HIDE_MENU = ["setting", "workbench"];

/**
 * @description: 生成树状菜单表
 * @param {*} list
 * @return {*}
 */
function getUserMenu(list, dictionary) {
  const userMenu = [];
  let homePage = {};
  let hideMenu = [];
  listToTree(list, userMenu, 0, dictionary);
  const menuNameList = list.map((item) => item.alias);
  const homeIndex = userMenu.findIndex((item) => item.alias === "home");
  if (homeIndex > -1) {
    homePage = list[homeIndex];
  }
  HIDE_MENU.forEach((name) => {
    const index = userMenu.findIndex((item) => item.alias === name);
    if (index > -1) {
      userMenu[index].hide = true;
      hideMenu.push(userMenu[index]);
    }
  });
  return { homePage, userMenu, hideMenu, menuNameList };
}

/**
 * @description: 给用户菜单分类到子应用
 * @param {*} list
 * @return {*}
 */
function getAppMenu(list) {
  let appMenu = { main: [] };
  list.forEach((item) => {
    let APPMenuKey =
      !item.app || MAIN_APP_NAMES.includes(item.app) ? "main" : item.app;
    if (appMenu[APPMenuKey]) {
      appMenu[APPMenuKey].push(item);
    } else {
      appMenu[APPMenuKey] = [item];
    }
  });
  // utils.consoleInfo(appMenu, "appMenu");
  return appMenu;
}

/**
 * @description: 一维数组生成树状结构
 * @param {Array} list
 * @param {Array} tree
 * @param {*} parentId
 * @return {*}
 */
function listToTree(list, tree, parentId, dictionary) {
  list.forEach((item) => {
    item.name = dictionary[item.name] || item.name;
    // 判断是否为父级菜单
    if (item.parent_id === parentId) {
      const child = {
        ...item,
        children: [],
      };
      // 迭代 list， 找到当前菜单相符合的所有子菜单
      listToTree(list, child.children, item.id, dictionary);
      // 删掉不存在 children 值的属性
      if (child.children.length <= 0) {
        delete child.children;
      }
      // 加入到树中
      tree.push(child);
    }
  });
}

export { getUserMenu, getAppMenu, HIDE_MENU };
